<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon users">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon merchants">
              <el-icon><Shop /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalMerchants }}</div>
              <div class="stats-label">商家数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalOrders }}</div>
              <div class="stats-label">总订单数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon revenue">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">¥{{ stats.totalRevenue }}</div>
              <div class="stats-label">总营业额</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单趋势</span>
            </div>
          </template>
          <v-chart :option="orderTrendOption" style="height: 300px;" />
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>营业额趋势</span>
            </div>
          </template>
          <v-chart :option="revenueTrendOption" style="height: 300px;" />
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="charts-row">
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>订单状态分布</span>
            </div>
          </template>
          <v-chart :option="orderStatusOption" style="height: 300px;" />
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>热门商家</span>
            </div>
          </template>
          <v-chart :option="topMerchantsOption" style="height: 300px;" />
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>用户增长</span>
            </div>
          </template>
          <v-chart :option="userGrowthOption" style="height: 300px;" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最新订单 -->
    <el-card class="recent-orders">
      <template #header>
        <div class="card-header">
          <span>最新订单</span>
          <el-button type="primary" size="small" @click="$router.push('/orders')">
            查看全部
          </el-button>
        </div>
      </template>
      
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="userName" label="用户" width="120" />
        <el-table-column prop="storeName" label="店铺" width="150" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import request from '@/api/request'
import { ElMessage } from 'element-plus'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 统计数据
const stats = ref({
  totalUsers: 0,
  totalMerchants: 0,
  totalOrders: 0,
  totalRevenue: '0'
})

// 最新订单
const recentOrders = ref([])

// 订单趋势图表配置
const orderTrendOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [820, 932, 901, 934, 1290, 1330, 1320],
    type: 'line',
    smooth: true,
    itemStyle: {
      color: '#409EFF'
    }
  }]
})

// 营业额趋势图表配置
const revenueTrendOption = ref({
  tooltip: {
    trigger: 'axis',
    formatter: '{b}: ¥{c}'
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [45000, 52000, 48000, 61000, 75000, 88000, 92000],
    type: 'bar',
    itemStyle: {
      color: '#67C23A'
    }
  }]
})

// 订单状态分布图表配置
const orderStatusOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  series: [{
    name: '订单状态',
    type: 'pie',
    radius: '50%',
    data: [
      { value: 1048, name: '已完成' },
      { value: 735, name: '配送中' },
      { value: 580, name: '制作中' },
      { value: 484, name: '已支付' },
      { value: 300, name: '已取消' }
    ],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    }
  }]
})

// 热门商家图表配置
const topMerchantsOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: ['麦当劳', '肯德基', '星巴克', '海底捞', '必胜客']
  },
  series: [{
    type: 'bar',
    data: [320, 280, 250, 220, 180],
    itemStyle: {
      color: '#E6A23C'
    }
  }]
})

// 用户增长图表配置
const userGrowthOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    data: [8500, 9200, 10100, 10800, 11500, 12580],
    type: 'line',
    smooth: true,
    areaStyle: {
      color: 'rgba(64, 158, 255, 0.2)'
    },
    itemStyle: {
      color: '#409EFF'
    }
  }]
})

const getStatusText = (status) => {
  const statusMap = {
    'paid': '已支付',
    'preparing': '制作中',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    'paid': 'warning',
    'preparing': 'primary',
    'delivering': 'info',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const data = await request.get('/admin/statistics')
    stats.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取最新订单 - 暂时注释掉，因为后端没有这个端点
const fetchRecentOrders = async () => {
  try {
    // 暂时使用模拟数据，因为后端没有 /admin/orders/recent 端点
    recentOrders.value = [
      {
        id: 1,
        orderNumber: 'ORD001',
        customerName: '张三',
        amount: 88.5,
        status: '已完成',
        createTime: new Date().toLocaleString()
      },
      {
        id: 2,
        orderNumber: 'ORD002',
        customerName: '李四',
        amount: 156.0,
        status: '进行中',
        createTime: new Date().toLocaleString()
      }
    ]
  } catch (error) {
    console.error('获取最新订单失败:', error)
    ElMessage.error('获取最新订单失败')
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    // 获取订单统计数据
    const orderData = await request.get('/admin/order-statistics')
    // 获取营收统计数据
    const revenueData = await request.get('/admin/revenue-statistics')
    
    // 更新订单趋势图表
    if (orderData) {
      orderTrendOption.value.series[0].data = orderData.trend || []
    }
    
    // 更新营收趋势图表
    if (revenueData) {
      revenueTrendOption.value.series[0].data = revenueData.trend || []
    }
    
    // 订单状态分布（使用模拟数据）
    orderStatusOption.value.series[0].data = [
      { value: 335, name: '已完成' },
      { value: 310, name: '进行中' },
      { value: 234, name: '已取消' },
      { value: 135, name: '待支付' }
    ]
  } catch (error) {
    console.error('获取图表数据失败:', error)
    ElMessage.error('获取图表数据失败')
  }
}

// 加载所有数据
const loadDashboardData = async () => {
  await Promise.all([
    fetchStats(),
    fetchRecentOrders(),
    fetchChartData()
  ])
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.merchants {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.orders {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.revenue {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.charts-row {
  margin-bottom: 20px;
}

.recent-orders {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>